//
//  String-extension.swift
//  jiurongjk
//
//  Created by xuewei on 16/12/2.
//  Copyright © 2016年 xuewei. All rights reserved.
//

import UIKit

extension String{
    
    //    //字符串转md5
    //    public func md5() ->String!{
    //        let str = self.cString(using: String.Encoding.utf8)
    //        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
    //        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
    //        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
    //        CC_MD5(str!, strLen, result)
    //        let hash = NSMutableString()
    //        for i in 0 ..< digestLen {
    //            hash.appendFormat("%02x", result[i])
    //        }
    //        result.deinitialize()
    //        return String(format: hash as String)
    //    }
    
//    //根据字体宽度，求高度
//    public func getHeightBy(fontSize:CGFloat, width:CGFloat, isBold:Bool) ->CGFloat {
//
//        if self.characters.count == 0 {
//            return 0
//        } else {
//            var tempRect:CGRect!
//            var attributes: [String : Any]?
//            if isBold {
//                attributes = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: fontSize)]
//            } else {
//                attributes = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: fontSize)]
//            }
//            tempRect = self.boundingRect(with: CGSize(width: width, height: CGFloat(DBL_MAX)), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
//            return tempRect.size.height
//        }
//
//    }
//
//    //行间距
//    public func getHeightBy(fontSize:CGFloat, width:CGFloat, lineSpacing:CGFloat, isBold:Bool) ->CGFloat {
//        if self.characters.count == 0 {
//            return 0
//        } else {
//            var tempRect:CGRect!
//            var attributes: [String : Any]?
//
//            let paraStyle = NSMutableParagraphStyle()
//            paraStyle.lineSpacing = lineSpacing
//            if isBold {
//                attributes = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: fontSize), NSAttributedStringKey.paragraphStyle : paraStyle]
//            } else {
//                attributes = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: fontSize), NSAttributedStringKey.paragraphStyle : paraStyle]
//            }
//            tempRect = self.boundingRect(with: CGSize(width: width, height: CGFloat(DBL_MAX)), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
//            return tempRect.size.height
//        }
//    }
    
    //是否为数字
    var isNumber: Bool{
        get {
            if self.isEmpty {
                return false
            }
            
            let chArr:[Character] = ["0","1","2","3","4","5","6","7","8","9","."]
            var dotCount = 0
            
            for ch in self.characters {
                if !chArr.contains(ch) {
                    return false
                }
                if ch == "." {
                    dotCount += 1
                }
            }
            
            //如果点号过多
            if dotCount > 1 {
                return false
            } else {
                return true
            }
        }
    }
    
    var isPureNumber:Bool {
        get {
            if self.isEmpty {
                return false
            }
            
            let chArr:[Character] = ["0","1","2","3","4","5","6","7","8","9"]
            
            for ch in self.characters {
                if !chArr.contains(ch) {
                    return false
                }
            }
            
            return true
        }
    }
    
    
    
    //是否手机号
    var isMobile:Bool {
        get {
            return (self.isPureNumber && self.count == 11)
        }
    }
    
    // 扩展String 字符串截取
    
    subscript (r: Range<Int>) -> String {
        get {
            let subStart = self.index(self.startIndex, offsetBy: r.lowerBound)
            let subEnd = self.index(self.startIndex, offsetBy: r.upperBound)
            return self.substring(with: subStart..<subEnd)
        }
    }
    func substring(from: Int) -> String {
        let end = self.characters.count
        return self[from..<end]
    }
    func substring(to:Int) -> String {
        return self[0..<to]
    }
    func substring(from: Int, length: Int) -> String {
        let end = from + length
        return self[from..<end]
    }
    func substring(from:Int, to:Int) ->String
    {
        return self[from..<to]
    }
    func substringFromStart(length: Int) -> String {
        return self[0..<length]
    }
    func substringFromEnd(length: Int) -> String {
        let c = self.characters.count - length
        return self[c..<self.characters.count]
    }
    
    func getWidthBy(text:String, fontSize:CGFloat) -> CGFloat {
        let lblTemp = UILabel(text: text, color: .white, fontSize: fontSize, isBold: false)
        return lblTemp.cb_width
    }
    
    //判断是否为纯数字
    func isPurnFloat() -> Bool {
        
        let scan: Scanner = Scanner(string: self)
        
        var val:Float = 0.00
        
        return scan.scanFloat(&val) && scan.isAtEnd
        
    }
    
    var normalDate:Date {
        get {
            let timeZone = TimeZone.init(identifier: "UTC")
            let formatter = DateFormatter()
            formatter.timeZone = timeZone
            formatter.locale = Locale.init(identifier: "zh_CN")
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter.date(from: self) ?? Date()
        }
    }
    
    var normalNumStr:String {
        get {
            if self.contains(".") {
                let arrNum = self.components(separatedBy: ".")
                let po = Int(arrNum.last ?? "0") ?? 0
                let it = Int(arrNum.first ?? "0") ?? 0
                if po == 0 {
                    return String(it)
                } else {
                    return String(it) + "." + String(po)
                }
            } else {
                return self
            }
        }
    }
    
    /*  1234567.89
     case none //1234567.89
     case decimal //1,234,567.89
     case currency //￥1,234,567.89
     case percent //123,456,789%
     case scientific //1.23456789E6
     case spellOut //一百二十三万四千五百六十七点八九
     @available(iOS 9.0, *)
     case ordinal //第123,4568
     @available(iOS 9.0, *)
     case currencyISOCode //CNY1,234,567.89
     @available(iOS 9.0, *)
     case currencyPlural//1,234,567.89人民币
     @available(iOS 9.0, *)
     case currencyAccounting//￥1,234,567.89
     */
    var moneyFormat:String {
        get {
            let format = NumberFormatter()
            //设置numberStyle（有多种格式）
            format.numberStyle = .decimal
            //转换后的string
            return format.string(from: NSNumber(value: Double(self) ?? 0)) ?? "0"
        }
    }
    
    //去除所有非数字部分
    var numberFormat:String {
        get {
            let arrNumCh:Array<Character> = ["0","1","2","3","4","5","6","7","8","9"]
            let strTemp:NSMutableString = NSMutableString(string: self)
            for ch in self {
                if arrNumCh.contains(ch) == false {
                    strTemp.deleteCharacters(in: strTemp.range(of: String([ch])))
                }
            }
            return strTemp as String
        }
    }
    
    //增加空白间隔
    func separateBySpace(count:Int) -> String {
        var strTemp = ""
        for (index, ch) in self.enumerated() {
            if index != 0 && index % count == 0 {
                strTemp += " "
            }
            strTemp += String(ch)
        }
        return strTemp as String
    }
    
    //银行卡号格式
    var bankcardFormat:String {
        get {
            return self.separateBySpace(count: 4)
        }
    }
    
    var trim:String {
        get {
            return self.replacingOccurrences(of: " ", with: "")
        }
    }
    
    //限制字符串最大长度
    func toMaxLen(len:Int) -> String {
        if self.characters.count > len {
            return self.substring(to: len)
        } else {
            return self
        }
    }
    
    var toDouble:Double {
        get {
            return Double(self) ?? 0.0
        }
    }
    
    var toInt:Int {
        get {
            return Int(self.toDouble)
        }
    }
    
    var toCGFloat:CGFloat {
        get {
            return CGFloat(self.toDouble)
        }
    }
    
}


